<?php

namespace app\order\logic;

use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

class OrderdeliverLogic
{
    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $limit           = $params['limit'] ?? 10;
        $buyer_email     = $params['buyer_email'] ?? "";
        $ship_status     = $params['ship_status'] ?? 0;
        $shop_id         = $params['shop_id'] ?? "";
        $split_status    = $params['split_status'] ?? "";
        $tracking_number = $params['tracking_number'] ?? "";
        $warehouse_id    = $params['warehouse_id'] ?? 0;

        $where = [];

        $update_time = $params['update_time'] ?? "";
        $create_time = $params['create_time'] ?? "";
        if (!empty($update_time)) {
            $where[]  = ['update_time', '>=', date('Y-m-d H:i:s',strtotime($update_time[0]))];
            $where[]  = ['update_time', '<=', date('Y-m-d H:i:s',strtotime($update_time[1]) + 3600*24-1)];
        }

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }



        if($split_status!==""){
            $where[] = ['split_status', '=', $split_status];
        }

        
        if (isset($params['order_id']) && !empty(trim($params['order_id']))) {  
            $order_ids_raw = trim($params['order_id']);  
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');  
            if (!empty($order_ids_filtered)) {  
                $where[] = ['order_id', 'in', $order_ids_filtered];  
            }  
        }



        if (isset($params['order_number']) && !empty(trim($params['order_number']))) {
            $order_numbers_raw = trim($params['order_number']);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            if (!empty($order_numbers_filtered)) {
                $where[] = ['honey_order_number', 'in', $order_numbers_filtered];
            }
        }


        if (!empty($buyer_email)) {
            $where[] = ['buyer_email', '=', $buyer_email];
        }
        if ($warehouse_id >= 1) {
            $where[] = ['warehouse_id_plan', '=', $warehouse_id];
        }
        
        if (!empty($ship_status)) {
            switch ($ship_status) {
                // 国内仓发货列表
                case 'DomesticWarehouseShipment':
                    $where[] = ['ship_status', '=', 0];
                    break;
                case 'AutomaticShipping':
                    //自动发货
                    //筛选仓库
                    $warehouse_id_plan = $params['warehouse_id_plan'] ?? 0;
                    if (!empty($warehouse_id_plan)) {
                        $where[] = ['warehouse_id_plan', '=', $warehouse_id_plan];
                    }
                    $where[] = ['ship_status', '=', 8];
                    $where[] = ['send_status', '=', 0];
                    
                    break;
                default:
                    $where[] = ['ship_status', '=', $ship_status];
            }
        }

        if (!empty($shop_id)) {
            $where[] = ['shop_id', '=', $shop_id];
        }

        if (!empty($tracking_number)) {
            $where[] = ['tracking_number', 'like', '%' . $tracking_number . '%'];
        }

        $order = ['update_time' => 'desc', 'create_time' => 'desc'];

        $list = Db::name('order_shopify_list')
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $lists = $list->items();

        foreach ($lists as $k=>$v) {
            switch ($v['ship_status']) {
                case '0':
                    $lists[$k]['ship_status'] = '准备国内仓发货';
                    $lists[$k]['ship_status_type'] = 'info';
                    break;
                case '1':
                    $lists[$k]['ship_status'] = '排队发货中';
                    $lists[$k]['ship_status_type'] = 'warning';
                    break;
                case '2':
                    $lists[$k]['ship_status'] = '发货异常';
                    $lists[$k]['ship_status_type'] = 'danger';
                    break;
                case '3':
                    $lists[$k]['ship_status'] = '回传物流单号';
                    $lists[$k]['ship_status_type'] = 'success';
                    break;
                case '4':
                    $lists[$k]['ship_status'] = '发货成功';
                    $lists[$k]['ship_status_type'] = 'success';
                    break;
                case '5':
                    $lists[$k]['ship_status'] = '已处理';
                    $lists[$k]['ship_status_type'] = 'success';
                    break;
                case '6':
                    $lists[$k]['ship_status'] = '发货异常标记成已处理';
                    $lists[$k]['ship_status_type'] = 'info';
                    break;
                case '8':
                    $lists[$k]['ship_status'] = '准备自动发货';
                    $lists[$k]['ship_status_type'] = '';
                    break;
                case '10':
                    $lists[$k]['ship_status'] = '补发订单';
                    $lists[$k]['ship_status_type'] = '';
                    break;
                default:
                    $lists[$k]['ship_status'] = '准备国内仓发货';
                    $lists[$k]['ship_status_type'] = 'info';
            }
            switch ($v['send_status']) {
                case '0':
                    $lists[$k]['send_status'] = '未发货';
                    $lists[$k]['send_status_type'] = 'info';
                    break;
                default:
                    $lists[$k]['send_status'] = '已发货';
                    $lists[$k]['send_status_type'] = 'success';
            }
            switch ($v['warehouse_id']) {
                case '1':
                    $lists[$k]['warehouse_id'] = 'JJS';
                    break;
                case '3':
                    $lists[$k]['warehouse_id'] = '金蚁';
                    break;
                case '4':
                    $lists[$k]['warehouse_id'] = '顺丰';
                    break;
                default:
                    $lists[$k]['warehouse_id'] = '暂无';
            }
            switch ($v['warehouse_id_plan']) {
                case '1':
                    $lists[$k]['warehouse_id_plan'] = 'JJS';
                    break;
                case '3':
                    $lists[$k]['warehouse_id_plan'] = '金蚁';
                    break;
                case '4':
                    $lists[$k]['warehouse_id_plan'] = '顺丰';
                    break;
                default:
                    $lists[$k]['warehouse_id_plan'] = '暂无';
            }
            $lists[$k]['order_number'] = $v['honey_order_number'];
        }
        
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单号', 'order_id'];
        $header[] = ['订单编号', 'order_number'];
        $header[] = ['SKU', 'sku'];
        $header[] = ['订单状态', 'ship_status_type'];
        $header[] = ['仓库', 'warehouse_id'];
        $header[] = ['推荐仓库', 'warehouse_id_plan'];
        $header[] = ['发货详情', 'msg'];
        $header[] = ['物流单号', 'tracking_number'];
        $header[] = ['客户昵称', 'buyer_name'];
        $header[] = ['邮箱', 'buyer_email'];
        $header[] = ['国家', 'country'];
        $header[] = ['州', 'state'];
        $header[] = ['城市', 'city'];
        $header[] = ['地址', 'address'];
        $header[] = ['创建时间', 'create_time'];
        $tableName = "OrderSelfShipment";

        $limit           = $params['limit'] ?? 10;
        $buyer_email     = $params['buyer_email'] ?? "";
        $ship_status     = $params['ship_status'] ?? 0;
        $shop_id         = $params['shop_id'] ?? "";
        $split_status    = $params['split_status'] ?? "";
        $tracking_number = $params['tracking_number'] ?? "";
        $warehouse_id    = $params['warehouse_id'] ?? 0;

        $where = [];

        $update_time = $params['update_time'] ?? "";
        $create_time = $params['create_time'] ?? "";
        if (!empty($update_time)) {
            $where[]  = ['update_time', '>=', date('Y-m-d H:i:s',strtotime($update_time[0]))];
            $where[]  = ['update_time', '<=', date('Y-m-d H:i:s',strtotime($update_time[1]) + 3600*24-1)];
        }

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }



        if($split_status!==""){
            $where[] = ['split_status', '=', $split_status];
        }


        if (isset($params['order_id']) && !empty(trim($params['order_id']))) {
            $order_ids_raw = trim($params['order_id']);
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');
            if (!empty($order_ids_filtered)) {
                $where[] = ['order_id', 'in', $order_ids_filtered];
            }
        }



        if (isset($params['order_number']) && !empty(trim($params['order_number']))) {
            $order_numbers_raw = trim($params['order_number']);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            if (!empty($order_numbers_filtered)) {
                $where[] = ['honey_order_number', 'in', $order_numbers_filtered];
            }
        }


        if (!empty($buyer_email)) {
            $where[] = ['buyer_email', '=', $buyer_email];
        }
        if ($warehouse_id >= 1) {
            $where[] = ['warehouse_id_plan', '=', $warehouse_id];
        }
        
        if (!empty($ship_status)) {
            switch ($ship_status) {
                // 国内仓发货列表
                case 'DomesticWarehouseShipment':
                    $where[] = ['ship_status', '=', 0];
                    break;
                case 'AutomaticShipping':
                    //自动发货
                    //筛选仓库
                    $warehouse_id_plan = $params['warehouse_id_plan'] ?? 0;
                    if (!empty($warehouse_id_plan)) {
                        $where[] = ['warehouse_id_plan', '=', $warehouse_id_plan];
                    }
                    $where[] = ['ship_status', '=', 8];
                    $where[] = ['send_status', '=', 0];
                    
                    break;
                default:
                    $where[] = ['ship_status', '=', $ship_status];
            }
        }

        if (!empty($shop_id)) {
            $where[] = ['shop_id', '=', $shop_id];
        }

        if (!empty($tracking_number)) {
            $where[] = ['tracking_number', 'like', '%' . $tracking_number . '%'];
        }

        $order = ['update_time' => 'desc', 'create_time' => 'desc'];

        $lists = Db::name('order_shopify_list')
            ->where($where)
            ->order($order)
            ->select()
            ->toArray();

        foreach ($lists as $k=>$v) {
            switch ($v['ship_status']) {
                case '0':
                    $lists[$k]['ship_status'] = '准备国内仓发货';
                    $lists[$k]['ship_status_type'] = 'info';
                    break;
                case '1':
                    $lists[$k]['ship_status'] = '排队发货中';
                    $lists[$k]['ship_status_type'] = 'warning';
                    break;
                case '2':
                    $lists[$k]['ship_status'] = '发货异常';
                    $lists[$k]['ship_status_type'] = 'danger';
                    break;
                case '3':
                    $lists[$k]['ship_status'] = '回传物流单号';
                    $lists[$k]['ship_status_type'] = 'success';
                    break;
                case '4':
                    $lists[$k]['ship_status'] = '发货成功';
                    $lists[$k]['ship_status_type'] = 'success';
                    break;
                case '5':
                    $lists[$k]['ship_status'] = '已处理';
                    $lists[$k]['ship_status_type'] = 'success';
                    break;
                case '6':
                    $lists[$k]['ship_status'] = '发货异常标记成已处理';
                    $lists[$k]['ship_status_type'] = 'info';
                    break;
                case '8':
                    $lists[$k]['ship_status'] = '准备自动发货';
                    $lists[$k]['ship_status_type'] = '';
                    break;
                case '10':
                    $lists[$k]['ship_status'] = '补发订单';
                    $lists[$k]['ship_status_type'] = '';
                    break;
                default:
                    $lists[$k]['ship_status'] = '准备国内仓发货';
                    $lists[$k]['ship_status_type'] = 'info';
            }
            switch ($v['send_status']) {
                case '0':
                    $lists[$k]['send_status'] = '未发货';
                    $lists[$k]['send_status_type'] = 'info';
                    break;
                default:
                    $lists[$k]['send_status'] = '已发货';
                    $lists[$k]['send_status_type'] = 'success';
            }
            switch ($v['warehouse_id']) {
                case '1':
                    $lists[$k]['warehouse_id'] = 'JJS';
                    break;
                case '3':
                    $lists[$k]['warehouse_id'] = '金蚁';
                    break;
                case '4':
                    $lists[$k]['warehouse_id'] = '顺丰';
                    break;
                default:
                    $lists[$k]['warehouse_id'] = '暂无';
            }
            switch ($v['warehouse_id_plan']) {
                case '1':
                    $lists[$k]['warehouse_id_plan'] = 'JJS';
                    break;
                case '3':
                    $lists[$k]['warehouse_id_plan'] = '金蚁';
                    break;
                case '4':
                    $lists[$k]['warehouse_id_plan'] = '顺丰';
                    break;
                default:
                    $lists[$k]['warehouse_id_plan'] = '暂无';
            }
            $lists[$k]['order_number'] = $v['honey_order_number'];
        }

        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导入
     * @author zhangheng
     */
    public function uploads($file=[])
    {
        if(!empty($file)){
            $upload = new Upload();
            $res = $upload->upload($file);
            if ($res['url']) {
                $return = $this->import_cost($res['url']);
                return json(DefaultResponse(200, true, '获取成功', $return));
            } else {
                return json(DefaultResponse(201, true, '上传文件失败', $res['msg']));
            }
        }else{
            return json(DefaultResponse(201, true, '文件为空'));
        }
    }

    //导入花费
    public function import_cost($url)
    {
        $url_arr = explode('storage/', $url);
        $data = Excel::import('storage/' . $url_arr[1]);
        unset($data[1]);
        foreach ($data as  $value) {
            //处理时间
            // $date = date_parse_from_format('Y-m-d', $value[2]);
            // $time = date('Y-m-d H:i:s', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
            // $arr_insert = [
            //     'advertiser_id' => isset($value[0]) ? $value[0] : 0,
            //     'spend' => isset($value[1]) ? $value[1] : 0,
            //     'stat_time_day' => $time ?  $time : 0,
            // ];
            // table('advertising')->insert($arr_insert);
        }
        return $url;
    }

    /**
     * 自动发货
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function automaticShipping($params = [])
    {

        $ids        = $params['ids'];
        $warehouse  = $params['warehouse_id'];
        $golden_ant = $params['golden_ant']??'2030';
        $fail_status= $params['status']??'';
        htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/automaticShipping/' . date('Ymd') . '.txt');
        if (empty($warehouse)) {
            return json(DefaultResponse(201, true, '仓库数据错误请刷新'));
        }

        $ids = is_array($ids) ? $ids : explode(',', $ids);

        // update 2024-06-15 此时更新状态值
        Db::name('order_shopify_list')->whereIn('id',$ids)->update(['send_status'=>1]);

        $where[] = ['o.id', 'in', $ids];
        $field = '*';

        $items = Db::name('order')
            ->field($field)
            ->where($where)
            ->select();
        $items = objectToArray($items);
        if($warehouse==1){
            //JJS自发货
            self::hwcSend($ids,$warehouse,$items);
        }else{
            if (!empty($items)){
                foreach ($items as $item) {
                    $item['tracking_beforehand'] = $item['tracking_beforehand']  ?: 0;
                    if ($item['status'] == 'AWAITING_SHIPMENT' && $item['fulfillment_type'] !== 'FULFILLMENT_BY_TIKTOK') {
                        if (in_array($item['tracking_beforehand'], [0, 1, 2])) {
                            /* //准备发货或者异常订单才能重新发货
                             $update['status']        = ConstantOrderService::$ship_status_waiting;
                             $update['warehouse_id']  = $warehouse;
                             Db::name('order_ship')->where('order_id', $item['order_id'])->update($update);*/

                            if ($warehouse == 1 && $item['brush_status'] == 'normal'){
                                $log                 = array();
                                $log['code']         = 1;
                                $log['order_id']     = $item['order_id'];
                                $log['shop_id']      = $item['shop_id'];
                                $log['time']         = time();
                                $log['warehouse_id'] = $warehouse;
                                OrderShipLogic::insertOrderShipLog($log);
                            }

                            $orderData = $item;
                            $orderData['warehouse_id'] = $warehouse;
                            $orderData['type'] = 1; //自发货
                            $orderData['fail_status']  = $fail_status;
                            if (in_array($warehouse, [2, 4, 5]) && $item['brush_status'] == 'normal' || $warehouse == 3){
                                // 队列处理
                                if ($warehouse == 3){
                                    $orderData['golden_ant'] = $golden_ant;
                                }
                                MqTaskPushLogic::mq_task_push(
                                    '',
                                    MqQueueName::QUEUE_ORDER_SHIPPING_QUEUE,
                                    $orderData,
                                    false
                                );
                            }
                        }
                    }
                }
            }
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }





    /**
     * @desc  海外仓发货JJS
     * @Date  2024-04-15
     * @author luckyXiong
     */
    public function hwcSend($ids,$warehouse,$items)
    {
        if(!$items)        return json(DefaultResponse(201, false, '暂无数据!'));
        foreach($items as $order){
            self::hwc_send_handle($order);
        }
    }



    /**
     * @desc  海外仓发货JJS
     * @Date  2024-04-15
     * @author luckyXiong
     */
    public function hwc_send_handle($order=[]){
        htmlLog(['order'=>$order],OPERATE_LOG . date('Ym') . '/hwc_send_handle/' . date('Ymd') . '.txt');
        $ParamsJson = self::get_params_jjs($order);
        $Params     = self::get_hwc_jjs($order);
        $msg_hwc    = $ParamsJson ? '':'海外仓找不到SKU：' . $order['skuinfo'];
        $ParamsJson["OrderDetail"][] = $Params;
        if($ParamsJson){
            Db::name('order_ship')->where('order_id', $order['order_id'])->update([
                    'status'=> 2,
                    'time'  => time(),
                    'msg'   => $msg_hwc
                ]
            );
            $log['code']         = 1;
            $log['order_id']     = $order['order_id'];
            $log['shop_id']      = $order['shop_id'];
            $log['time']         = time();
            $log['warehouse_id'] = 1;;
            OrderShipLogic::insertOrderShipLog($log);
        }

        // 重量小于0.448的全选小包
        if ($Params['zWeight'] > 0.448) {
            $ParamsJson["ShipperService"] = "796"; //运输方式 大包
        } else {
            $ParamsJson["ShipperService"] = "797"; //运输方式 小包
        }

        $ParamsJson = (is_array($ParamsJson)) ? json_encode($ParamsJson, JSON_UNESCAPED_UNICODE) : $ParamsJson;
        $url        = Config('Logisticskey.JJS.url');
        $token      = Config('Logisticskey.JJS.token');
        $data =[
            'token'      => $token,
            'ParamsJson' => $ParamsJson,
        ];

        $data     = http_build_query($data);
        $response = HttpUtil::posturlJJS($url, $data);
        $return   = json_decode(json_encode(simplexml_load_string($response)), true);
        $return   = $return[0]??'';
        if(!$return) return json(DefaultResponse(201, false, '暂无数据!'));
        $return = json_decode($return,'true');
        if(isset($return['OrderNo']) && $return['OrderNo']){
            $return['code']    = 3;
            $return['msg']     = "回传物流单号";
            $return['data']    = $return['TrackingNo'];
            $return['return1'] = json_encode($ParamsJson, true);
            Db::name('order')->where('order_id', $order['order_id'])->update(
                [
                    'status'              => 'AWAITING_COLLECTION',
                    'tracking_number'     =>  $return['TrackingNo'],
                ]
            );
            Db::name('order_ship')->where('order_id', $order['order_id'])->update(
                [
                    'status'              =>  4,
                    'tracking_number'     =>  $return['TrackingNo'],
                    'msg'                 =>  '物流单号回传完成',
                    'time'                =>  time(),
                ]
            );
            $log['code']         = 3;
            $log['order_id']     = $order['order_id'];
            $log['shop_id']      = $order['shop_id'];
            $log['msg']          = '物流单号回传完成';
            $log['time']         = time();
            $log['warehouse_id'] = 1;;
            self::insertOrderShipLog($log);
        }else{
            Db::name('order_ship')->where('order_id', $order['order_id'])->update(
                [
                    'status'              =>  2,
                    'msg'                 =>  $return['msg'],
                    'time'                =>  time(),
                ]
            );
            $log['code']         = 2;
            $log['order_id']     = $order['order_id'];
            $log['shop_id']      = $order['shop_id'];
            $log['time']         = time();
            $log['msg']          = $return['msg'];
            $log['warehouse_id'] = 1;;
            self::insertOrderShipLog($log);
        }
    }




    /**
     * @desc  获取组装数据
     * @Date  2024-04-15
     * @author luckyXiong
     */
    private function get_params_jjs($order=[]){
        return [
            "Style"         =>1,
            "CsRefNo"       =>$order['order_id']??'',
            "StockID"       =>"35",
            "ConsigneeName" =>$order['name']??'',
            "CountryCode"   =>$order['region_code']??'',
            "State"         =>$order['state']??'',
            "City"          =>$order['city']??'',
            "Zipcode"       =>$order['postal_code']??'',
            "Address1"      =>$order['address_detail']??'',
            "Contact"       =>$order['phone_number']??'',
            "Signature"     =>"0",
            "Insurance"     =>"0",
        ];
    }

    /**
     * @desc  获取组装数据
     * @Date  2024-04-15
     * @author luckyXiong
     */
    private function get_hwc_jjs($order=[]){
        $product_hwc =  Db::name('product_hwc')->where('CnName', $order['skuinfo'])->find();
        $zWeight = 0;
        $OrderDetail["CnName"]   = $product_hwc['CnName'];
        $OrderDetail["EnName"]   = $product_hwc['EnName'];
        $OrderDetail["SKU"]      = $product_hwc['SKU'];
        $OrderDetail["Quantity"] = get_colours_num($order['skuinfo']);
        $OrderDetail["Weight"]   = $product_hwc['Weight'];
        $OrderDetail["zWeight"] = (float)number_format((float)$zWeight + (float)$OrderDetail["Weight"], 2, '.', '');
        $OrderDetail["Length"] = $product_hwc['Length'];
        $OrderDetail["Width"] = $product_hwc['Width'];
        $OrderDetail["High"] = $product_hwc['High'];
        $OrderDetail["Price"] = $product_hwc['Price'];
        $OrderDetail["CnName"] = $product_hwc['CnName'];
        $OrderDetail["HSCode"] = "";
        $OrderDetail["Origin"] = "";
        return $OrderDetail;
    }













    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc find
     * @author zhangheng
     */
    public function find($params = [])
    {
        $data = [];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

}
